<!--
 * @Author: 卢景滔
 * @Date: 2021-12-20 17:19:36
 * @LastEditTime: 2021-12-21 14:37:25
 * @LastEditors: 卢景滔
 * @Description: Worder-详细示例
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Worder-详细示例</title>
  </head>
  <body>
    <h1>Worder-详细示例</h1>
    <h3>使用调试面板查看</h3>
    <script type="text/javascript">
      // 兼容性判断
      if (!Worker) {
        throw new Error('当前浏览器不支持多线程')
      }

      // 创建子线程
      const childThread = new Worker('child/ChildThread.js')

      // 向子线程发送数据
      childThread.postMessage({ cmd: 'to child', data: 'How are you, child?' })

      // 向子线程发送数据
      childThread.postMessage({ cmd: `to child's child`, data: `How are you, child's child?` })

      // 向子线程发送数据
      childThread.postMessage({ cmd: 'test error', data: 'tell me what error' })

      // 监听子线程信息
      childThread.addEventListener('message', (e) => {
        const res = e.data
        switch (res.cmd) {
          case 'to father':
            console.log('主线程收到子线程信息: ', res.data)
            break

          case `to father's father`:
            console.log('主线程收到子线程信息: ', res.data)
            break

          default:
            console.log('主线程收到其它信息：', e.data)
            break
        }
      })

      // 监听子线程信息
      childThread.addEventListener('error', (e) => {
        console.log('主线程捕获子线程错误: ', e)
      })

    </script>
  </body>
</html>
